((window, undefined) => {
  let that;
  class Game {
    constructor(map) {
      this.food = new Food();
      this.snake = new Snake();
      this.map = map;
      that = this;
    }
    // 游戏开始
    start () {
      this.food.render(this.map);
      this.food.render(this.map);
      this.food.render(this.map);
      this.snake.render(this.map);
      Game.runSnake();
      Game.bindKey();
    }

    // 定义一个私有函数 让蛇动起来
    static runSnake () {
      const timer = setInterval(function () {
        // 定时器函数内部函数指向window
        that.snake.move();
        that.snake.remove(that.map);
        that.snake.render(that.map);
        // 每次新位置都要判断是否吃到食物 食物消失 自己增加一节
        // 当前蛇头的位置
        let headX = that.snake.body[0].x;
        let headY = that.snake.body[0].y;
        // 记录食物的坐标
        //var foodX = that.food.x;
        //var foodY = that.food.y;
        // 蛇的坐标
        let hx = headX * that.snake.width;
        let hy = headY * that.snake.height;
        // 判断蛇头碰到某一个食物 
        for (let i = 0; i < that.food.elements.length; i++) {
          if (that.food.elements[i].offsetLeft === hx && that.food.elements[i].offsetTop === hy) {
            // 吃到食物
            that.food.remove(that.map, i);
            //重新渲染食物
            that.food.render(that.map);
            // 添加一个新的蛇节
            let last = that.snake.body[that.snake.body.length - 1];
            that.snake.body.push({
              x: last.x,
              y: last.y,
              color: last.color
            });
          }
        }
        // 每次移动都要判断
        let maxX = that.map.offsetWidth / that.snake.width;
        let maxY = this.map.offsetHeight / that.snake.height;

        // 判断
        if (headX < 0 || headX >= maxX || headY < 0 || headY >= maxY) {
          clearInterval(timer);
          alert("Game Over");
        }
      }, 150);
    }

    // 封装一个键盘方法 
    static bindKey () {
      document.addEventListener('keydown', function (e) {
        e = e || window.event;
        // 37 左 38 top 39 right 40 bottom
        switch (e.keyCode) {
          case 37:
            that.snake.direction = "left";
            break;
          case 38:
            that.snake.direction = "top";
            break;
          case 39:
            that.snake.direction = "right";
            break;
          case 40:
            that.snake.direction = "bottom";
        }
      });
    }

  }

  window.Game = Game;
})(window);